﻿using System;
using MySql.Data.MySqlClient;
using System.Data;

namespace CzfSDK
{
	public class MysqlPool : ConcurrentCzfPool<MySqlConnection>
	{
		public static MysqlPool current;

		public MysqlPool (string connString, int init = 10, int max = 20, int timeout = 60000)
		{
			Init (() => {
				MySqlConnection conn = new MySqlConnection (connString);
				conn.Open ();
				return conn;
			},(MySqlConnection conn) => {
				if(conn != null)
					conn.Close();
			}, init, max, timeout);
			current = this;
		}

		public int ExecInt(string sql, params MySqlParameter[] param){
			DataRow dr = ExecDataRow (sql, param);
			return Convert.ToInt32(dr[0]);
		}

		public string ExecString(string sql, params MySqlParameter[] param){
			DataRow dr = ExecDataRow (sql, param);
			if (dr != null)
				return Convert.ToString(dr[0]);
			else
				return null;
		}

		public DataRow ExecDataRow(string sql, params MySqlParameter[] param)
		{
			DataTable dt = ExecDataTable (sql, param);
			if (dt != null && dt.Rows.Count > 0)
				return dt.Rows [0];
			else
				return null;
		}

		public DataTable ExecDataTable(string sql, params MySqlParameter[] param)
		{
			return ExecDataTable (sql, CommandType.Text, param);
		}

		public int ExecuteNonQuery(string sql, params MySqlParameter[] param)
		{
			return ExecuteNonQuery (sql, CommandType.Text, param);
		}

		public int ExecuteNonQuery(string sql, CommandType commandType, params MySqlParameter[] param)
		{
			int ret = 0;
			Exec ((conn) =>{
				MySqlCommand command = new MySqlCommand (sql, conn);
				command.Parameters.AddRange (param);
				command.CommandType = commandType;
				ret = command.ExecuteNonQuery();
			});
			return ret;
		}

		public DataTable ExecDataTable(string sql, CommandType commandType, params MySqlParameter[] param)
		{
			DataTable dt = new DataTable();
			Exec ((conn) =>{
				MySqlCommand command = new MySqlCommand (sql, conn);
				command.Parameters.AddRange (param);
				command.CommandType = commandType;
				MySqlDataAdapter da = new MySqlDataAdapter (command);
				da.Fill (dt);
			});
			return dt;
		}
	}
}

